package oakclub.utility;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.TimeoutException;

public class SocketUtility
{
    private static final int BUFFER_SIZE = 1024;

    public static Socket connect(String host, int port) throws IOException
    {
        return new Socket(host, port);
    }

    public static BufferedWriter getWriter(Socket socket) throws IOException
    {
        return new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    }

    public static BufferedReader getReader(Socket socket) throws IOException
    {
        return new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    public static void write(BufferedWriter writer, String str) throws IOException
    {
        writer.write(str);
        writer.newLine();
        writer.flush();
    }

    /**
     * @param timeout in milliseconds
     */
    public static String read(BufferedReader reader, int timeout) throws IOException, InterruptedException, TimeoutException
    {
        StringBuilder response = new StringBuilder();
        char[] buffer = new char[BUFFER_SIZE];

        // wait for response
        int wait = 0;
        while(!reader.ready())
        {
            wait += 100;
            if(wait > timeout)
            {
                throw new TimeoutException("socket read timeout");
            }
            Thread.sleep(100);
            continue;
        }

        // read response
        do
        {
            int charsRead = reader.read(buffer, 0, BUFFER_SIZE);
            response.append(buffer, 0, charsRead);
        }
        while(reader.ready());

        return response.toString();
    }

    public static void close(Socket socket) throws IOException
    {
        socket.close();
    }
}
